<template>
  <div class="avue-map">
    <el-dialog
      class="avue-map__dialog"
      width="60%"
      append-to-body
      modal-append-to-body
      title="选择坐标"
      @close="handleClose"
      :visible="box"
    >
      <div class="avue-map__content" v-if="box">
        <div class="area">
          <el-select
            class="area-select"
            ref="province"
            v-model="result.province"
            placeholder="请选择"
            @change="changeProvince"
          >
            <el-option
              v-for="item in area.province"
              :key="item.label"
              :label="item.label"
              :value="item.value.id"
            ></el-option>
          </el-select>
          <el-select
            class="area-select"
            ref="city"
            v-model="result.city"
            placeholder="请选择"
            @change="changeCity"
          >
            <el-option
              v-for="item in area.city"
              :key="item.label"
              :label="item.label"
              :value="item.value.id"
            ></el-option>
          </el-select>
          <el-select
            class="area-select"
            ref="area"
            v-model="result.district"
            placeholder="请选择"
            @change="changeArea"
          >
            <el-option
              v-for="item in area.area"
              :key="item.label"
              :label="item.label"
              :value="item.value.id"
            ></el-option>
          </el-select>
        </div>

        <!-- <el-popover
          placement="bottom"
          width="100%"
          trigger="focus"
          @show="showHover"
          :disabled="disablePop"
          ref="searchPop"
        >
          <ul class="sugg-ul">
            <li v-for="(item,index) in searchItems" :key="index" @click="handleSelect(item)">
              <div class="sugg-item">
                <span class="sugg-name">{{item.title}}</span>
                <span class="sugg-address">{{item.address}}</span>
              </div>
            </li>
          </ul>
          <el-input
            class="avue-map__content-input"
            id="map__input"
            size="small"
            v-model="address"
            clearable
            placeholder="输入关键字选取地点"
            @input="querySearch(address)"
            slot="reference"
            :disabled="! enableInput"
          ></el-input>
        </el-popover>-->
        <el-input
          class="avue-map__content-input"
          id="map__input"
          size="small"
          v-model="address"
          clearable
          placeholder="输入关键字选取地点"
          slot="reference"
          :disabled="! enableInput"
        >
          <el-button @click="querySearch(address)" slot="append" icon="el-icon-search"></el-button>
        </el-input>

        <el-input
          class="avue-map__content-input"
          size="small"
          v-model="result.address_info"
          clearable
          placeholder="输入楼层/门牌号"
          :disabled="! enableInput"
          ref="addressInfo"
        ></el-input>
        <div class="avue-map__content-box" ref="mapBox">
          <div id="map__container" class="avue-map__content-container" tabindex="0"></div>
          <div id="map__result" class="avue-map__content-result"></div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */

import provinceData from "@/util/area/province";
import cityData from "@/util/area/city";
import areaData from "@/util/area/area";
import { successMsg, errorMsg } from "@/util/message"
import { isNull } from "@/util/util";

export default {
  name: 'addressMap',
  props: ['box', 'mapResult'],
  mounted() {
    // this.$nextTick(() => this.init())
    // this.initProvice()
  },
  computed: {
    textTitle() {
      return this.poi.name === undefined ? "选择坐标" : "重新选择";
    },
    enableInput() {
      let flag = (!isNull(this.result.province)) && (!isNull(this.result.city)) && (!isNull(this.result.district))
      return flag;
    },
    disablePop() {
      if (this.searchItems.length > 0)      {
        this.searchBoxVis = true
        return false;
      }
      return true;
    },
    fullAddress() {
      return this.currentObj.province.item.label
        + this.currentObj.city.item.label
        + this.currentObj.area.item.label
        + this.address
        + this.result.address_info
    },
  },
  watch: {
    box() {
      if (this.box)      {
        this.$nextTick(() => {
          this.handleInit()
          // this.init()
          // this.initProvice()
        })
      }
    },

  },
  data() {
    return {
      poi: {},
      address: '',
      map: '',
      searchBoxVis: false,
      showBox: this.box,
      area: {
        province: [],
        city: [],
        area: []
      },
      currentObj: {
        province: {
          item: '',
          index: ''
        },
        city: {
          item: '',
          index: ''
        },
        area: {
          item: '',
          index: ''
        }
      },
      searchItems: {},
      result: {
        province: '',
        city: '',
        district: '',
        address: '',
        address_info: '',
        full_address: '',
        zip: '',
        latitude: '',
        longitude: '',
      }
    }
  },
  methods: {
    handleClose() {
      this.searchItems = {}
      this.$emit('close', '');
    },
    //初始化所有相关的东西
    handleInit() {
      this.updateMapResult()
      this.checkProvinceParams()
      this.initMap()

      if (!isNull(this.result.longitude) && !isNull(this.result.latitude))      {
        setTimeout(() => {
          var point = new BMap.Point(this.result.longitude, this.result.latitude);
          this.refreshPoint(point)
        }, 1000);
      }

    },
    // 初始化函数
    checkProvinceParams() {
      this.area.province = provinceData

      if (!isNull(this.result.province))      {
        //获取省份数据
        this.area.province.forEach((element, index) => {
          if (element.value.id === this.result.province)          {
            this.currentObj.province.item = element
            this.currentObj.province.index = index
            return false
          }
        });

        if (!isNull(this.result.city))        {
          this.area.city = cityData[this.currentObj.province.index]  //设置城市
          this.area.city.forEach((element, index) => {

            if (element.value.id === this.result.city)            {
              this.currentObj.city.item = element
              this.currentObj.city.index = index
              return false
            }
          });
        }

        if (!isNull(this.result.district))        {
          let provinceIndex = this.currentObj.province.index
          let cityIndex = this.currentObj.city.index
          this.area.area = areaData[provinceIndex][cityIndex]

          this.area.area.forEach((element, index) => {
            if (element.value.id === this.result.district)            {
              this.currentObj.area.item = element
              this.currentObj.area.index = index
              return false
            }
          });
        }
      }
    },
    updateMapResult() {
      this.result.province = this.mapResult.province
      this.result.city = this.mapResult.city
      this.result.district = this.mapResult.district
      this.result.address = this.mapResult.address
      this.result.address_info = this.mapResult.address_info
      this.result.latitude = this.mapResult.latitude
      this.result.longitude = this.mapResult.longitude
      this.address = this.result.address
    },
    initMap() {
      const safe = this;
      var map = new BMap.Map("map__container");    // 创建Map实例
      this.map = map
      //添加地图类型控件
      map.addControl(new BMap.MapTypeControl({
        mapTypes: [
          BMAP_NORMAL_MAP,
          BMAP_HYBRID_MAP
        ]      }));

      let location = this.currentObj.province.item.label + this.currentObj.city.item.label

      if (isNull(this.currentObj.province.item.label))
      {
        location = "福州"
      }

      if (!isNull(this.currentObj.area.item.label))
      {
        location += this.currentObj.area.item.label
      }

      map.centerAndZoom(location, 16);
      //map.centerAndZoom(new BMap.Point(26.075219, 119.363799), 15);
      map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
      this.searchItems = ''

      map.addEventListener("click", function(e){
        safe.selectMyPoint(e)
      });
    },
    initProvice() {
      this.area.province = provinceData
    },
    //选择当前位置
    selectMyPoint(e) {
      this.result.address = this.address
      this.result.latitude = e.point.lat
      this.result.longitude = e.point.lng

      //刷新坐标
      var pp = e.point;
      this.refreshPoint(pp)
    },
    changeProvince(id) {
      // 清除城市和地区的参数
      this.result.city = ''
      this.result.district = ''
      this.address = ''
      this.result.address = ''
      this.result.address_info = ''
      this.searchItems = ''


      // 查找元素
      this.area.province.forEach((element, index) => {
        if (element.value.id === id)        {
          this.currentObj.province.item = element
          this.currentObj.province.index = index
          return false
        }
      });

      this.area.city = cityData[this.currentObj.province.index]  //设置城市
    },
    changeCity(id) {
      this.result.district = ''
      this.result.address = ''
      this.result.address_info = ''
      this.address = ''
      this.searchItems = ''

      this.area.city.forEach((element, index) => {
        this.result.address = ''
        this.result.address_info = ''
        this.address = ''
        if (element.value.id === id)        {
          this.currentObj.city.item = element
          this.currentObj.city.index = index
          return false
        }
      });

      let provinceIndex = this.currentObj.province.index
      let cityIndex = this.currentObj.city.index
      this.area.area = areaData[provinceIndex][cityIndex]
    },
    changeArea(id) {
      this.result.address = ''
      this.result.address_info = ''
      this.address = ''
      this.searchItems = ''

      this.area.area.forEach((element, index) => {
        if (element.value.id === id)        {
          this.currentObj.area.item = element
          this.currentObj.area.index = index
          return false
        }
      });

      this.refreashMap()


    },
    findSelectItem(index, data) {
      var objIndex = data.findIndex((item) => {
        return item.value.id === index;
      });
      return objIndex;
    },
    refreashMap() {
      this.initMap()
    },
    querySearch(queryString) {

      let vm = this
      if (isNull(queryString)) return;
      var local = new BMap.LocalSearch(this.map, { //智能搜索
        onSearchComplete: filterSearch
      });
      local.search(queryString);

      function filterSearch() {
        var pp = local.getResults().getPoi(0).point;
        let zoom = vm.map.getZoom()
        vm.map.centerAndZoom(pp, zoom);
        vm.map.addOverlay(new BMap.Marker(pp));
        //vm.searchItems = local.getResults().Ar
      }
    },
    showHover() {
      this.querySearch(this.text)
    },
    handleSelect(item) {
      this.address = item.title
      this.result.address = item.title
      this.result.latitude = item.point.lat
      this.result.longitude = item.point.lng

      //刷新坐标
      var pp = item.point;
      this.refreshPoint(pp)
      this.$refs.addressInfo.$el.getElementsByTagName('input')[0].focus();
    },
    refreshPoint(point) {
      this.map.clearOverlays();
      let zoom = this.map.getZoom()
      this.map.centerAndZoom(point, zoom);
      this.map.addOverlay(new BMap.Marker(point));
    },
    // 确认提交信息
    handleSubmit() {
      // 进行验证
      if (isNull(this.result.province)) return errorMsg(this, '省份不能为空')
      if (isNull(this.result.city)) return errorMsg(this, '城市不能为空')
      if (isNull(this.result.district)) return errorMsg(this, '地区不能为空')

      if (isNull(this.address)) return errorMsg(this, '地址不能为空')
      if (isNull(this.result.latitude) || isNull(this.result.longitude)) return errorMsg(this, '坐标选择出现错误')

      this.result.address = this.address

      let aletMsg = '当前选择的地址为:' + this.fullAddress + ',是否确认?'
      this.$confirm(aletMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.result.full_address = this.fullAddress
        //发送给上一级
        this.$emit('confirm', '')
        this.box = false
        this.handleClose()
      }).catch(() => {

      });
    }
  }
}
</script>

<style lang="scss">
.avue-map {
  &__submit {
    width: 100%;
  }
  &__content {
    &-input {
      margin-bottom: 10px;
    }
    &-box {
      position: relative;
    }
    &-container {
      width: 100%;
      height: 450px;
    }
    &-result {
      display: block !important;
      position: absolute;
      top: 0;
      right: -8px;
      width: 250px;
      height: 450px;
      overflow-y: auto;
    }
  }
}

.area {
  display: flex;
  width: 600px;
  margin-bottom: 20px;
}
.area-select {
  margin-right: 20px;
}
.wide-dropdown {
  width: 600px !important;
}

.sugg-ul {
  overflow: auto;
  height: 280px;
}

.sugg-item {
  border-bottom: 1px solid #eee;
  cursor: pointer;
  padding: 10px;
}

.sugg-item:hover {
  background-color: #cee0fc;
}

.sugg-name {
}
.sugg-address {
  margin-left: 10px;
  font-size: 90%;
  color: #999;
  margin-left: 5px;
}
</style>

